package com.ronglian.register_mini_program.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ronglian.register_mini_program.model.RegisterUser;
import com.ronglian.register_mini_program.model.WxConstant;
import com.ronglian.register_mini_program.model.WxUserAccessTokens;
import com.ronglian.register_mini_program.result.ResultBody;
import com.ronglian.register_mini_program.service.AccessTokenService;
import com.ronglian.register_mini_program.service.ActivityService;
import com.ronglian.register_mini_program.service.RegisterService;
import com.ronglian.register_mini_program.service.UserService;
import com.ronglian.register_mini_program.util.*;
import org.apache.http.HttpResponse;
import org.apache.http.entity.StringEntity;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/wx")
@Api(tags = "微信", description = "微信")
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Successful — 请求已完成"),
        @ApiResponse(code = 400, message = "请求中有语法问题，或不能满足请求"),
        @ApiResponse(code = 401, message = "未授权客户机访问数据"),
        @ApiResponse(code = 404, message = "服务器找不到给定的资源；文档不存在"),
        @ApiResponse(code = 500, message = "服务器不能完成请求")}
)
public class WXLoginController {

    @Value("${wx_app_id}")
    private final static String wx_app_id = "wx40b8e0d1d6ca6b27";
    @Value("${wx_app_secrect}")
    private final static String wx_app_secrect = "6f2c00b45cee154e1ce7822aac90f2a5";

    @Autowired
    RegisterService registerService;
    @Autowired
    ActivityService activityService;
    @Autowired
    UserService userService;
    @Autowired
    AccessTokenService accessTokenService;

    @ApiOperation(value = "微信小程序获取openid", notes = "微信小程序获取openid")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "code", value = "code", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "appid", value = "appid", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "appSecret", value = "appSecret", required = true)
    })
    @RequestMapping(value = "/jscode2session", method = RequestMethod.GET)
    public ResultBody jscode2session(
            @RequestParam("code") String code,
            @RequestParam("appid") String appid,
            @RequestParam("appSecret") String appSecret
    ) {
        try {
            System.out.println("appid" + WxConstant.wx_app_id);
            System.out.println("appsecret" + WxConstant.wx_app_secrect);
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=authorization_code";
            JSONObject jsonObj = HttpClientUtils.httpGet(url);
            System.out.println(jsonObj);
            //添加openid到用户表里，先查询，再添加
            String openid = (String) jsonObj.get("openid");
            System.out.println("获取到了openid" + openid);
            String session_key = (String) jsonObj.get("session_key");
            System.out.println("获取到了sessionkey" + session_key);
            if (openid == null) {
                return new ResultBody("500", "openid不得为空！");
            }
            RegisterUser user = userService.findByOpenId(openid);
//            Map map = new HashMap();
            System.out.println("我获取了用户，创建了map!!!!!");
            if (user == null) {
                user = new RegisterUser();
                user.setOpen_id(openid);
                user.setSession_key(session_key);
                userService.insert(user);
                user = userService.findByOpenId(openid);

                jsonObj.put("uid", user.getUid());
                System.out.println("增添用户，返回uid" + user.getUid());
            } else {
                user.setSession_key(session_key);
                userService.update(user);
                user = userService.findByOpenId(openid);
                jsonObj.put("uid", user.getUid());
                System.out.println("修改用户，返回uid" + user.getUid());
            }
            System.out.println("我要返回openid了！！！！！！！！" + JsonUtils.objectToJson(jsonObj));
            return new ResultBody(jsonObj);
        } catch (Exception e) {
            System.out.println(e.toString());
            System.out.println("-------------------------------------------------");
            System.out.println(e.getMessage());
            System.out.println("-------------------------------------------------");
            e.printStackTrace();
            return new ResultBody("500", "微信小程序获取openid失败！");
        }

    }


    @ApiOperation(value = "微信小程序获取access_token", notes = "微信小程序获取access_token")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "appid", value = "appid", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "appSecret", value = "appSecret", required = true)
    })
    @RequestMapping(value = "/getWxAccesToken", method = RequestMethod.GET)
    public ResultBody getWxAccesToken(
            @RequestParam("appid") String appid,
            @RequestParam("appSecret") String appSecret
    ) {

        try {

            String access_token = "";
            if (!StringUtils.isBlank(appid)) {
                System.out.println("appid不是空哦！！！！！！！"+appid);
                //无则添加 有则比较有效期和修改
                WxUserAccessTokens accessTokens = new WxUserAccessTokens();
                System.out.println("我要验证为什么task传过来的appid查不了"+appid);
               accessTokenService.findByAppid(appid);
                if (accessTokens != null) {
                    long beforeTime = accessTokens.getUpdate_time().getTime();
                    //比较现在的日期增加1.5后的时间>7200*0.75    1.5小时的话还大于access token的生成时间，说明就该换了
                    long nowtime = new Date().getTime();
                    long nowt = System.currentTimeMillis();
                    long beforeTwoHourTime = DateUtil.addSomeHours(1.5).getTime();


                    long interval = beforeTwoHourTime - beforeTime;
                    //7200s=7200*1000ms
                    long standard_interval = (long) (7200 * 0.75 * 1000);
                    boolean bool = interval > standard_interval;
                    System.out.println("access_token是否过期" + bool);
                    if (bool || StringUtils.isBlank(accessTokens.getWx_access_token())) {
                        System.out.println("access_token过期了呀！！！！！！！！");
                        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appSecret;
                        JSONObject jsonObj = HttpClientUtils.httpGet(url);
                        System.out.println(jsonObj);
                        access_token = (String) jsonObj.get("access_token");
                        Integer expires_in = (Integer) jsonObj.get("expires_in");
                        accessTokens.setWx_app_secret(appSecret);
                        accessTokens.setWx_access_token(access_token);
                        accessTokens.setUpdate_time(new Date());
                        accessTokenService.update(accessTokens);
                        accessTokens = accessTokenService.findByAppid(appid);

                    } else {
                        System.out.println("access_token还能用！！！！！！！！");
                        access_token = accessTokens.getWx_access_token();
                    }

                } else {
                    System.out.println("重新获取access_token了！！！！！！！！！");
                    //获取access_token
                    String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appSecret;
                    JSONObject jsonObj = HttpClientUtils.httpGet(url);
                    System.out.println(jsonObj);
                    access_token = (String) jsonObj.get("access_token");
                    Integer expires_in = (Integer) jsonObj.get("expires_in");
                    WxUserAccessTokens new_accessTokens = new WxUserAccessTokens();
                    new_accessTokens.setExpires_in(expires_in);
                    new_accessTokens.setWx_access_token(access_token);
                    new_accessTokens.setWx_app_id(appid);
                    new_accessTokens.setWx_app_secret(appSecret);
                    new_accessTokens.setCreate_time(new Date());
                    new_accessTokens.setUpdate_time(new Date());
                    accessTokenService.insert(new_accessTokens);
                }
            }

//        objectMapper.readvalu
            System.out.println("要返回access_token了" + access_token);
            return new ResultBody(access_token);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultBody("500", "微信小程序获取access_token失败！");
        }

    }

    @ApiOperation(value = "微信小程序获取二维码", notes = "微信小程序获取二维码")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "appid", value = "appid", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "appSecret", value = "appSecret", required = true)
    })
    @RequestMapping(value = "/getwxacode", method = RequestMethod.GET)
    public ResultBody getwxacode(
            @RequestParam("appid") String appid,
            @RequestParam("appSecret") String appSecret
    ) throws IOException {

        try {
            String path = "";
            String qrcodePath = "";
            //         //先传appid和appsecret自动生成或传回access_token然后去请求二维码
            ResultBody resultBody = getWxAccesToken(appid, appSecret);
            if (resultBody.getResult() != null) {
                String access_token = (String) resultBody.getResult();
                //获取二维码
//            WxqrcodeBody wxqrcodeBody = new WxqrcodeBody();

//            wxqrcodeBody.setScene(UUIDUtil.getUUId());
//            String json = JsonUtils.objectToJson(wxqrcodeBody);
                String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + access_token;
                Map<String, Object> params = new HashMap<>();
                params.put("scene", UUIDUtil.getUUId());
                params.put("page", "pages/index/index");
                params.put("width", 430);

                CloseableHttpClient httpClient = HttpClientBuilder.create().build();

                HttpPost httpPost = new HttpPost(url);
                httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
                String body = JSON.toJSONString(params);
                StringEntity entity = null;
                try {
                    entity = new StringEntity(body);

                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    return new ResultBody("500", "初始化参数失败！");
                }

                httpPost.setEntity(entity);
                HttpResponse response;

                try {
                    response = httpClient.execute(httpPost);
                } catch (IOException e) {

                    e.printStackTrace();
                    return new ResultBody("500", "请求失败！");
                }
                InputStream inputStream = null;
                try {
                    inputStream = response.getEntity().getContent();
                } catch (IOException e) {
                    e.printStackTrace();
                    return new ResultBody("500", "获取二维码失败！");
                }
                if (OSUtil.isWindows()) {
                    path = "D:\\upload\\";

                }
                if (OSUtil.isLinux()) {
                    path = "/ftp/images/qrcode/";
                }
                File targetFile = new File(path);
                if (!targetFile.exists()) {

                    targetFile.mkdirs();
                    targetFile.setWritable(true);
                    targetFile.setReadable(true);
                    targetFile.setExecutable(true);
                }
                String trueFileName = String.valueOf(System.currentTimeMillis());
                FileOutputStream out = null;
                ;
                ;
                path = path + trueFileName + "5.png";

                try {
//                File file = new File(path);
//                file.setExecutable(true);
//                file.setReadable(true);
//                file.setWritable(true);
                    out = new FileOutputStream(path);
                } catch (FileNotFoundException e) {

                    e.printStackTrace();
                    return new ResultBody("500", "微信小程序获取二维码失败！");
                }

                byte[] buffer = new byte[8192];
                int bytesRead = 0;
                while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }

                out.flush();
                out.close();

            }
            return new ResultBody(path);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultBody("500", "微信小程序获取二维码失败！");
        }

    }

    @ApiOperation(value = "发送模板信息", notes = "发送模板信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "appid", value = "appid", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "appSecret", value = "appSecret", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "touser", value = "接收者（用户）的 openid", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "template_id", value = "所需下发的模板消息的id", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "page", value = "点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。", required = false),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "form_id", value = "表单提交场景下，为 submit 事件带上的 formId；支付场景下，为本次支付的 prepay_id", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "activity_name", value = "模板内容，活动名称", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "activity_address", value = "模板内容，活动地址", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "activity_time", value = "模板内容，活动截至时间", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "activity_mark", value = "模板内容，备注", required = true)
    })
    @RequestMapping(value = "/sendTemplateMessage", method = RequestMethod.POST)
    public ResultBody sendTemplateMessage(
            @RequestParam("appid") String appid,
            @RequestParam("appSecret") String appSecret,
            @RequestParam("touser") String touser,
            @RequestParam("template_id") String template_id,
            @RequestParam("page") String page,
            @RequestParam("form_id") String form_id,
            @RequestParam("activity_name") String activity_name,
            @RequestParam("activity_address") String activity_address,
            @RequestParam("activity_time") String activity_time,
            @RequestParam("activity_mark") String activity_mark
    ) throws IOException {

        try {
            String str = "";
            JSONObject jsonObject = null;

            //         //先传appid和appsecret自动生成或传回access_token然后去请求二维码
            System.out.println("发送模板之前的appid==="+appid+"=====appsecret==="+appSecret);
            ResultBody resultBody = getWxAccesToken(appid, appSecret);
            System.out.println("Access_token==========" + resultBody.getResult());
            if (!resultBody.getResult().equals("null")) {
                String access_token = (String) resultBody.getResult();
                System.out.println("发送模板获取token:==========" + access_token);
                //获取二维码
//            WxqrcodeBody wxqrcodeBody = new WxqrcodeBody();

//            wxqrcodeBody.setScene(UUIDUtil.getUUId());
//            String json = JsonUtils.objectToJson(wxqrcodeBody);
                String url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" + access_token;
                Map<String, Object> params = new HashMap<>();
                params.put("touser", touser);
                params.put("template_id", template_id);
                params.put("page", page);
                params.put("form_id", form_id);
                Map<String, Object> data = new HashMap<>();
                Map<String, Object> value1 = new HashMap<>();
                Map<String, Object> value2 = new HashMap<>();
                Map<String, Object> value3 = new HashMap<>();
                Map<String, Object> value4 = new HashMap<>();
                value1.put("value", activity_name);
                value2.put("value", activity_address);
                value3.put("value", activity_time);
                value4.put("value", activity_mark);
                data.put("keyword1", value1);
                data.put("keyword2", value2);
                data.put("keyword3", value3);
                data.put("keyword4", value4);
                params.put("data", data);

                CloseableHttpClient httpClient = HttpClientBuilder.create().build();
                System.out.println("touser来了！！！！！！=====" + touser);
                System.out.println("form_id来了！！！！！！=====" + form_id);
                System.out.println("template_id来了！！！！！！=====" + template_id);
                HttpPost httpPost = new HttpPost(url);
                httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json;charset=utf-8");
                String body = JSON.toJSONString(params);
                System.out.println("发送模板信息======请求的json数据：" + body);
                StringEntity entity = new StringEntity(body, "UTF-8");
                entity.setContentEncoding("UTF-8");

                httpPost.setEntity(entity);
                HttpResponse response;
                try {
                    response = httpClient.execute(httpPost);
                    System.out.println("httpPost请求之后的响应！！！！！！！");
                } catch (IOException e) {
                    e.printStackTrace();
                    return new ResultBody("500", "请求失败！");
                }
                try {
                    // 读取服务器返回过来的json字符串数
                    str = EntityUtils.toString(response.getEntity(), "UTF-8");
                    System.out.println("读取服务器返回过来的json字符串数======" + str);
                    // 把json字符串转换成json对象
                    jsonObject = JSONObject.parseObject(str);
                    if (jsonObject!=null&&jsonObject.get("errmsg").equals("ok")){

                        System.out.println("模板发送成功！");
                    }else {
                        System.out.println("模板发送失败！原始是"+jsonObject.get("errmsg"));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    return new ResultBody("500", "发送模板信息失败！");
                }
            }
            return new ResultBody(jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultBody("500", "发送模板信息失败！");
        }

    }

}